//
//  BKUserLoginController.m
//  bestkeep
//
//  Created by windCould on 16/11/16.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "BKUserLoginController.h"
#import "BKMyCommon.h"
#import "BKUserRecordNumTableView.h"
#import "BKUserInputNumView.h"
#import "BkCustomNavBarView.h"
#import "BKUserStatusInfo.h"
#import "BKUserUnitRequestAPI.h"
#import "BKUserLoginHeaderView.h"
#import "BKUseLoginFooterView.h"
#import "BKUserRegisterViewController.h"
#import "BKUserBindingViewController.h"
#import "BKUserFindPwdViewController.h"
#import "BKUserMobileConfigInfo.h"
#import "Sign.h"
#import "BKUserBindingViewController.h"
#import "BKUserCodeFormat.h"
#import "UT_User.h"
//使用友盟进行第三方登录
#import "UMSocialWechatHandler.h"
#import "BKUserThirdLoginMannager.h"


@interface BKUserLoginController ()<BKUserInputNumViewDelegate,BKUserRecordNumTableViewDelegate,UIGestureRecognizerDelegate,BKUseLoginFooterViewDelegate,UINavigationControllerDelegate>

@property (nonatomic,strong)BkCustomNavBarView * cusNavBarView;
@property (nonatomic,strong)BKUserLoginHeaderView * loginHeadView;
@property (nonatomic,strong)UIButton * cacelBtn;
@property (nonatomic,strong)BKUserRecordNumTableView * recordNumListView;
@property (nonatomic,strong)BKUserInputNumView * userNumView;
@property (nonatomic,strong)BKUserInputNumView * userPwdView;
@property (nonatomic,strong)BKUseLoginFooterView * loginFooterView;

@property (nonatomic,strong)UIButton * loginBtn;
@property (nonatomic,strong)UIButton * registerBtn;
@property (nonatomic,strong)UIButton * forgetBtn;
@property (nonatomic,copy)NSString * userNum;//用户名
@property (nonatomic,copy)NSString * userPwd;//用户密码


@property (nonatomic,copy)BKLoginSuccessBlock  successBlock;
//三方登录
@property (nonatomic, strong) TencentOAuth *tencentOAuth;
@property (nonatomic, strong) NSMutableArray *permissionArray;
@property (nonatomic, copy) NSString * QQName;
@property (nonatomic, copy) NSString * WiXinName;


@property (nonatomic,strong)NSDictionary * loginParDict;
@property (nonatomic,strong)NSDictionary * bindDict;


@end

@implementation BKUserLoginController


+(instancetype)userGotoLoginWithBlcok:(BKLoginSuccessBlock)finishBlock
{
    BKUserLoginController * loginVc = [[BKUserLoginController alloc]initWithBlock:finishBlock];
    return loginVc;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapExitKeyboard)];
    tap.delegate = self;
    [self.view addGestureRecognizer:tap];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginByThird) name:NSNotificationBKUserRelogin object:nil];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
   [self.navigationController setNavigationBarHidden:YES animated:animated];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

#pragma mark =========================UINavigationControllerDelegate========================

//-(void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
//{
//    BOOL isHide = [viewController isKindOfClass:[self class]];
//    
//    [self.navigationController setNavigationBarHidden:isHide animated:YES];
//}

-(instancetype)init
{
    if ([super init]) {
        
        [self setUpViews];
    }
    
    return self;
}

-(instancetype)initWithBlock:(BKLoginSuccessBlock)successBlock
{
    self = [self init];
    if (self) {
        
        self.successBlock = successBlock;
    }
    
    return self;
}

#pragma mark =========================Function===================================

-(void)cancelLogin
{
    [self.view endEditing:YES];
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)loginByThird
{
     [self bundleThiedAccount:_loginParDict withBind:_bindDict];
}

-(void)dissmissLoadingView
{
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [BKIndicationView dismiss];
    });

}


-(void)goToLoginBtnClick
{
    [self.view endEditing:YES];
    _userNum = self.userNumView.userNumTextField.text;
    _userPwd = self.userPwdView.userNumTextField.text;
    
    if (![BKUserCodeFormat parameterValueIsNotNilAndZeroLengthWithContentStr:_userNum]) {
        
        [HUD showErrorMessage:@"请输入用户名"];
        return;
    }
    
    if (![BKUserCodeFormat parameterValueIsNotNilAndZeroLengthWithContentStr:_userPwd]) {
        
        [HUD showErrorMessage:@"请输入密码"];
        return;
    }
    BKUserMobileConfigInfo * mobileConfig = [[BKUserMobileConfigInfo alloc]init];
    
//    /*
//     * 保存UUID
//     */
//    NSString *SERVICE_NAME = @"com.utouu.bestkeep";//最好用程序的bundle id
//    NSString * str =  [BKKeychain valueForKey:SERVICE_NAME ];  // 从keychain获取数据
//    if ([str length]<=0){
//        
//        str  = mobileConfig.device_udid;
//        [BKKeychain setObject:str forKey:SERVICE_NAME ];  // 往keychain添加数据
//        
//    }
    
    [BKIndicationView showInView:self.view];
//    NSLog(@"8888888-------%@",mobileConfig.device_udid);
    [UT_User loginWithUserName:_userNum password:_userPwd deviceUDID:mobileConfig.device_udid deviceType:mobileConfig.device_type deviceToken:mobileConfig.device_token version:mobileConfig.version appName:mobileConfig.app_name callBack:^(id responce, NSError *error) {

        if (error) {
            
            [self dissmissLoadingView];
            if (error.code==502) {
                [HUD showErrorMessage:@"服务器开小差了，请稍后再试！"];
            }else{
                [HUD showErrorMessage:error.localizedDescription];
            }
        } else {
            
            BOOL result = [[responce objectForKey:@"success"] boolValue];
            NSLog(@"%@",[responce objectForKey:@"msg"]);
            if (![responce objectForKey:@"msg"]) {
                
                [self dissmissLoadingView];
                [HUD showErrorMessage:@"服务器端发生错误"];
            } else if (result) {
                
                NSString * tgt = [[responce objectForKey:@"data"]objectForKey:@"tgt"];
                BKUserStatusInfo * userStatusInfo =[BKUserStatusInfo currentUser];
                
                [userStatusInfo.realm beginWriteTransaction];
                
                userStatusInfo.userNum = _userNum;
                userStatusInfo.userPwd = _userPwd;
                userStatusInfo.TGT = tgt;
                
                [userStatusInfo.realm commitWriteTransaction];
                
                //获取st
                [BKUserUnitRequestAPI  getSTWithTGT:tgt service:@"http://api.utouu.com" completeBlock:^(id obj, NSString  *data, NSError *error) {
                    
                    if (data) {
                        
                        //获取用户信息
                        [BKUserUnitRequestAPI getUserInfoCompleteBlock:^(id obj, NSError *error) {
                            
                            [self dissmissLoadingView];
                            if (obj) {
                                
                                BKUserRequestResultModel * result = obj;
                                
                                if ( [result.success isEqualToString:@"1"] ) {
                                    
                                    //获取用户支付密钥
                                    [BKUserLoginController getUserSecretKey:^(id obj) {
                                        
                                    }];
                                    
                                    [HUD showSuccessMessage:@"登录成功"];
                                    
                                    if (self.successBlock) {
                                        
                                        self.successBlock();
                                    }
                                    
                                    [self cancelLogin];
                                    
                                } else {
                                    
                                    [HUD showErrorMessage:result.msg];
                                    
                                }
                            } else {
                                
                                if (error.code==502) {
                                    [HUD showErrorMessage:@"服务器开小差了，请稍后再试！"];
                                }else{
                                    [HUD showErrorMessage:error.localizedDescription];
                                }
                            }
                            
                        }];
                    } else {
                        
                        
                    }
                    
                }];
            } else {
                
                NSString * resultStr = [responce objectForKey:@"msg"];
                [HUD showErrorMessage:resultStr];
                [self dissmissLoadingView];
            }
            
        }
    }];
    

    
    
    
   /*
    [BKUserUnitRequestAPI userLoginWithUserNum:_userNum password:_userPwd showTiPInView:self.view compeleteBlock:^(id obj, NSError *error) {
        
        [BKIndicationView dismiss];
        if (obj) {
            
        BKUserRequestResultModel * result = obj;
        
        if ( [result.success isEqualToString:@"1"] ) {
            
            [HUD showSuccessMessage:@"登录成功"];
            
            if (self.successBlock) {
            
               self.successBlock();
            }
            
            [self cancelLogin];
            
        } else {
        
            [HUD showErrorMessage:result.msg];
        
        }
        } else {
        
            [HUD showErrorMessage:error.localizedDescription];
        }
        
        
    }];
   */
    
}
#pragma mark =========================UIGestureRecognizerDelegate=================

//防止tap 手势 导致collectionView item 点击不响应的问题
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    
    if ([NSStringFromClass([touch.view.superview class]) isEqualToString:@"UITableViewCell"]) {
        
        return NO;
    } else {
        
        return YES;
    }
    
}


-(void)tapExitKeyboard
{
    self.userNumView.endEditing = YES;
    self.userPwdView.endEditing = YES;
}


#pragma mark =========================BKUserInputNumViewDelegate======================

-(void)bKUserInputNumView:(BKUserInputNumView *)bKUserInputNumView inputTextFieldContent:(NSString *)content
{
//    switch (bKUserInputNumView.usageType) {
//        case 0:{
//            
//            self.userNum = content;
//            break;
//        }
//        case 1:{
//            
//            self.userPwd = content;
//            break;
//        }
//            
//        default:
//            break;
//    }
}

-(void)bKUserInputNumView:(BKUserInputNumView *)bKUserInputNumView btnSelect:(BOOL)isSelect
{
    self.recordNumListView.hidden = !isSelect;
    [self layoutViewsWithSelect:isSelect];
}

#pragma mark =========================快速注册 找回密码====================================
-(void)mobileRegister
{
    BKUserRegisterViewController * registerVc = [[BKUserRegisterViewController alloc]init];
    [self.navigationController pushViewController:registerVc animated:YES];
}

-(void)forgetPassword
{
    BKUserFindPwdViewController * findPwd = [[BKUserFindPwdViewController alloc]init];
    [self.navigationController pushViewController:findPwd animated:YES];
}

#pragma mark =========================BKUseLoginFooterViewDelegate======================
-(void)bkUseLoginFooterView:(BKUseLoginFooterView *)userLoginFooterView wechatLogin:(UIButton *)btn
{
 
   [BKUserThirdLoginMannager getUserInfoForPlatform:@"wechat" result:^(UMSocialUserInfoResponse * obj, NSError *error) {
       
       if (!error) {
           
           BKUserMobileConfigInfo * config = [[BKUserMobileConfigInfo alloc]init];
           
           NSString *udid = config.device_udid;
           NSString *time = [Sign getSystemTime];
           NSString *accessToken = obj.accessToken;
           NSString *openID = obj.openid;
           NSString *app_version = config.version;
           NSString *unionID = obj.uid;
           NSString *devicetToken = config.device_token;
           NSString *openType = @"2";
           
           if (devicetToken == nil) {
               
               devicetToken = @"";
           }
           
           //原始参数表->用于生成sign
           NSDictionary *dictOrginalPara = @{@"open_id":openID,
                                             @"open_type":openType,
                                             };
           //生成sign
           NSString *strSign = [Sign sign:dictOrginalPara time:time];
           //accept_agreemt 协议 push_platform推送类型 1.信鸽 2.阿里云 confirm_change 是否确认换绑设备 confirm_code确认换绑输入验证码
           
           //登录参数
           NSDictionary *dicLoginPara =@{@"open_id":openID,
                                         @"open_type":openType,
                                         @"device_udid":udid,
                                         @"device_type":@"10",
                                         @"version":app_version,
                                         @"device_token":devicetToken,
                                         @"app_name":config.app_name,
                                         @"access_token":accessToken,
                                         @"time":time,
                                         @"sign":strSign,
                                         @"accept_agreemt":@"1",
                                         @"push_platform":@"1",
                                         @"union_id":unionID,
                                         };
           
           //下一个页面所传参数
           
           NSDictionary *weiXinBindDict = @{@"open_id":openID,
                                            @"open_type":openType,
                                            @"device_type":@"10",
                                            @"access_token":accessToken,
                                            @"sign":strSign,
                                            };
           
           _loginParDict = dicLoginPara;
           _bindDict = weiXinBindDict;
           
           [self bundleThiedAccount:dicLoginPara withBind:weiXinBindDict];
       } else {
       
           NSLog(@"%@",error.localizedDescription);
           
       }
   }];
   
    
}

-(void)bkUseLoginFooterView:(BKUseLoginFooterView *)userLoginFooterView qqLogin:(UIButton *)btn
{
    [BKUserThirdLoginMannager getUserInfoForPlatform:@"QQ" result:^(UMSocialUserInfoResponse * obj, NSError *error) {
       
        if (!error) {
        
        BKUserMobileConfigInfo * config = [[BKUserMobileConfigInfo alloc]init];
       
        NSString *udid = config.device_udid;
        NSString *time = [Sign getSystemTime];
        NSString *accessToken =obj.accessToken;
        NSString *openID = obj.openid;
        NSString *app_version = config.version;
        NSString *devicetToken = config.device_token;
        NSString *openType = @"1";
        
        if (devicetToken == nil) {
            devicetToken = @"";
        }
        //原始参数表->用于生成sign
        NSDictionary *dictOrginalPara = @{@"open_id":openID,
                                          @"open_type":openType,
                                          };
        //生成sign
        NSString *strSign = [Sign sign:dictOrginalPara time:time];
        //accept_agreemt 协议 push_platform推送类型 1.信鸽 2.阿里云 confirm_change 是否确认换绑设备 confirm_code确认换绑输入验证码
        //登录参数
        NSDictionary *dicLoginPara =@{
                                      @"open_id":openID,
                                      @"open_type":openType,
                                      @"device_udid":udid,
                                      @"device_type":@"10",
                                      @"version":app_version,
                                      @"device_token":devicetToken,
                                      @"app_name":@"bestkeep",
                                      @"access_token":accessToken,
                                      @"time":time,
                                      @"sign":strSign,
                                      @"accept_agreemt":@"1",
                                      @"push_platform":@"1",
                                      };
        //绑定登录界面所需传参的字典
        NSDictionary *bindDict = @{
                                   @"open_id":openID,
                                   @"open_type":openType,
                                   @"device_type":@"10",
                                   @"access_token":accessToken,
                                   @"sign":strSign,
                                   };
        
        _loginParDict = dicLoginPara;
        _bindDict = bindDict;
        [self bundleThiedAccount:dicLoginPara withBind:bindDict];
     } else {
        
         NSLog(@"%@",error.localizedDescription);
        
        }
            
     }];
}

-(void)bkUseLoginFooterView:(BKUseLoginFooterView *)userLoginFooterView type:(NSInteger)typeValue
{
   
    if (typeValue == 1) {
        
        [self bkUseLoginFooterView:nil qqLogin:nil];
    }
    
    if (typeValue == 3) {
        
        [self bkUseLoginFooterView:nil wechatLogin:nil];
    }
    
    
}

#pragma mark =========================BKUserRecordNumTableViewDelegate===========

-(void)bkUserRecordNumTableView:(BKUserRecordNumTableView *)bkUserRecordNumTableView userSelectRecordNum:(NSString *)userNum
{
    
    
    
}


#pragma mark =========================第三方登录===================================

#pragma mark -- 判断第三方账号有没有绑定bk账号

-(void)bundleThiedAccount:(NSDictionary *)dicParam withBind:(NSDictionary *)bind
{
   // [BKIndicationView dismiss];
    [BKIndicationView showInView:self.view];
    [BKUserUnitRequestAPI checkThirdAccount:dicParam mycallBack:^(id obj, NSError *error) {
        [BKIndicationView dismiss];
        NSDictionary *dataDict = obj;
        
        NSLog(@"-------%@",dataDict);
        NSDictionary *userDict = dataDict[@"data"];
        NSString *tgt = userDict[@"tgt"];
        __weak typeof(self) weakself = self;
        NSString *msg = [dataDict objectForKey:@"msg"];
        if ([[dataDict objectForKey:@"success"] boolValue]) {
            
            BKUserStatusInfo * userInfo = [BKUserStatusInfo currentUser];
            
            [userInfo.realm beginWriteTransaction];
            userInfo.TGT = tgt;
            [userInfo.realm commitWriteTransaction];
            
            [self ThirdAccountSuccessWith:tgt];
        }
        
        else
        {
            if (IOS8) {
                
                UIAlertController *alertAc = [UIAlertController alertControllerWithTitle:@"提示" message:msg preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction *action = [UIAlertAction actionWithTitle:@"绑定已有账号" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                    BKUserBindingViewController * bindinVc = [[BKUserBindingViewController alloc] init];
                    bindinVc.infoDict = bind;
                    [weakself.navigationController pushViewController:bindinVc animated:YES];
                }];
                
                [alertAc addAction:action];
                UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"去注册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [weakself mobileRegister];
                }];
                
                [alertAc addAction:action2];
                [weakself presentViewController:alertAc animated:YES completion:nil];
            }
            
            else
            {
                UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:msg delegate:self cancelButtonTitle:@"绑定已有账号" otherButtonTitles:@"去注册", nil];
                alertView.tag = 3000;
                [alertView show];
            }
            
            
        }
        
        NSLog(@"%@------obj",obj);
        
    }];
    
}

#pragma mark -alertView代理
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 3000) {
        
        if (buttonIndex == 0) {
            
            BKUserBindingViewController * bindinVc = [[BKUserBindingViewController alloc] init];
            bindinVc.infoDict = self.bindDict;
            [self.navigationController pushViewController:bindinVc animated:YES];
        }
        if (buttonIndex == 1) {
            
            [self mobileRegister];
        }
    }
}
-(void)ThirdAccountSuccessWith:(NSString *)tgt
{
    [BKIndicationView showInView:self.view];
    [BKUserUnitRequestAPI getSTWithTGT:tgt service:@"http://api.test.utouu.com" completeBlock:^(id obj, NSString * data, NSError * error) {
       
        if (data) {
            
            [BKUserUnitRequestAPI getUserInfoCompleteBlock:^(id obj, NSError *error) {
                [BKIndicationView dismiss];
                if (obj) {
                    
                    BKUserRequestResultModel * result = obj;
                    if ([result.success isEqualToString:@"1"]) {
                        
                        if (self.successBlock) {
                            
                            self.successBlock();
                        }
                        
                        [self cancelLogin];
                        //获取用户支付密钥
                        [BKUserLoginController getUserSecretKey:^(id obj) {
                            
                        }];
                        [HUD showSuccessMessage:@"登录成功"];
                    } else {
                    
                        [HUD showErrorMessage:result.msg];
                 }
                } else {
                
                    
                    [HUD showErrorMessage:@"网络请求失败"];
                }
                
            }];
        } else {
        
            [BKIndicationView dismiss];
        }
        
    }];
}

#pragma mark =========================布局========================================

-(void)setUpViews
{
    //自定义navigationbar
    
    _cacelBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    _cacelBtn.titleLabel.font = UIBarButtonItemFont;
    [_cacelBtn setImage:[[UIImage imageNamed:@"BK_My_Gbutton_"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [_cacelBtn setTitleColor:RGBCOLOR(51, 51, 51, 1) forState:UIControlStateNormal];
    [_cacelBtn addTarget:self action:@selector(cancelLogin) forControlEvents:UIControlEventTouchUpInside];
    
    
    _loginHeadView = [[BKUserLoginHeaderView alloc]initWithFrame:CGRectZero];
    [self.view addSubview:_loginHeadView];
    [self.view addSubview:_cacelBtn];
    
    _loginFooterView = [[BKUseLoginFooterView alloc]initWithFrame:CGRectZero];
    _loginFooterView.myDelegate = self;
    [self.view addSubview:_loginFooterView];
    
    _userNumView = [[BKUserInputNumView alloc]initWithFrame:CGRectZero leftIcon:[UIImage imageNamed:@"BK_My_butter_icon_02"] rightIcons:nil usageType:InputviewUsageTypeAccount];
    _userNumView.myDelegate = self;
    BKUserStatusInfo * stausInfo = [BKUserStatusInfo currentUser];
    if (stausInfo.userNum && ![stausInfo.userNum isEqualToString:@""]) {
        
        _userNum = stausInfo.userNum;
    }
    _userNumView.contentStr = stausInfo.userNum;
    _userNumView.keyTpe = UIKeyboardTypeNumbersAndPunctuation;
    _userNumView.bordLineShowType = HideBottomLineAndBottomLine;
    _userNumView.placeHolderString = @"请输入用户名";
    [self.view addSubview:_userNumView];
    
    _userPwdView = [[BKUserInputNumView alloc]initWithFrame:CGRectZero leftIcon:[UIImage imageNamed:@"BK_My_butter_icon_03"] rightIcons:nil usageType:InputviewUsageTypeSecreat];
    _userPwdView.myDelegate = self;
    _userPwdView.isSecurity = YES;
    _userPwdView.keyTpe =  UIKeyboardTypeNumbersAndPunctuation;
    _userPwdView.placeHolderString = @"请输入密码";
    [self.view addSubview:_userPwdView];
    
    //用户登录账号记录
    
    //    _recordNumListView = [[BKUserRecordNumTableView alloc]initWithFrame:CGRectZero];
    //    _recordNumListView.recordDelegate = self;
    //    _recordNumListView.hidden = YES;
    //    [self.view addSubview:_recordNumListView];
    
    //登录按钮
    _loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _loginBtn.titleLabel.font = UIFontBoldCustom(18);
    [_loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    _loginBtn.layer.cornerRadius = 3;
    _loginBtn.layer.masksToBounds = YES;
    [_loginBtn addTarget:self action:@selector(goToLoginBtnClick) forControlEvents:UIControlEventTouchUpInside];
    _loginBtn.backgroundColor = BK_MY_COLOR_01;
    [self.view addSubview:_loginBtn];
    
    //注册
    _registerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_registerBtn setTitle:@"手机快速注册" forState: UIControlStateNormal];
    _registerBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [_registerBtn setTitleColor:HexColor(0xB2B2B2) forState:UIControlStateNormal];
    [_registerBtn addTarget:self action:@selector(mobileRegister) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_registerBtn];
    
    //忘记密码
    _forgetBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _forgetBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [_forgetBtn setTitleColor:HexColor(0xB2B2B2) forState:UIControlStateNormal];
    [_forgetBtn setTitle:@"找回密码" forState:UIControlStateNormal];
    [_forgetBtn.titleLabel setTextAlignment:NSTextAlignmentRight];
    [_forgetBtn addTarget:self action:@selector(forgetPassword) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_forgetBtn];
    
    [self layoutViewsWithSelect:NO];
}

-(void)layoutViewsWithSelect:(BOOL)isSelect
{
    CGFloat   ListH = isSelect == YES ? 50:0;
    
    
    [_cacelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(@(20));
        make.left.mas_equalTo(self.view.mas_left).offset(0);
        make.size.mas_equalTo(CGSizeMake(50, 50));
    }];
    

    [_loginHeadView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(self.view.mas_top).offset(0);
        make.left.mas_equalTo(self.view.mas_left).offset(20);
        make.right.mas_equalTo(self.view.mas_right).offset(-20);
        make.height.mas_equalTo(@((ScreenHeight * 175)/665));
        
    }];
    
    
    [_userNumView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(_loginHeadView.mas_bottom).offset(45);
        make.left.mas_equalTo(self.view.mas_left).offset(0);
        make.right.mas_equalTo(self.view.mas_right).offset(0);
        make.height.mas_equalTo(@(50));
    }];
    
    [_recordNumListView mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(self.userNumView.mas_bottom).offset(0);
        make.left.mas_equalTo(self.view.mas_left).offset(0);
        make.right.mas_equalTo(self.view.mas_right).offset(0);
        make.height.mas_equalTo(@(ListH));
        
    }];
    
    [_userPwdView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(_userNumView.mas_bottom).offset(0);
        make.left.mas_equalTo(self.view.mas_left).offset(0);
        make.right.mas_equalTo(self.view.mas_right).offset(0);
        make.height.mas_equalTo(@(50));
    }];
    
    
    [_loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(_userPwdView.mas_bottom).offset(34);
        make.left.mas_equalTo(self.view.mas_left).offset(33);
        make.right.mas_equalTo(self.view.mas_right).offset(-33);
        make.height.mas_equalTo(@(45));
    }];
    
    [_registerBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(_loginBtn.mas_bottom).offset(10);
        make.left.mas_equalTo(self.view.mas_left).offset(33);
        make.size.mas_equalTo(CGSizeMake(80, 20));
        
    }];
    
    [_forgetBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(_loginBtn.mas_bottom).offset(10);
        make.right.mas_equalTo(self.view.mas_right).offset(-33);
        make.size.mas_equalTo(CGSizeMake(55, 20));
    }];
    
    
    [_loginFooterView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(self.view.mas_left).offset(0);
        make.right.mas_equalTo(self.view.mas_right).offset(0);
        make.bottom.mas_equalTo(self.view.mas_bottom).offset(0);
        make.height.mas_equalTo(@((135 * ScreenHeight)/665));
    }];
    
}

//获取用户支付密钥
+ (void)getUserSecretKey:(void(^)(id obj))block {
    
    //登录成功后 获取用户支付密钥
    [BKUserUnitRequestAPI getUserSecretBlock:^(id obj, NSError *error) {
        if (obj) {
            NSDictionary *dic = obj[@"data"];
             NSLog(@"获取用户支付密钥：%@",obj);
            BKUserStatusInfo * userStatusInfo =[BKUserStatusInfo currentUser];
            
            [userStatusInfo.realm beginWriteTransaction];
            
            userStatusInfo.userSecretKey = dic[@"secretKey"];
            userStatusInfo.userValidTime = dic[@"validTime"];
            
            for (NSDictionary *tempDic in dic[@"payWays"]) {
                
                BKUserPayWay *userPayWay = [[BKUserPayWay alloc] init];
                
                userPayWay.userPayWayValue = tempDic[@"value"];
                userPayWay.userPayWayName = tempDic[@"name"];
                
                [userStatusInfo.userPayWays addObject:userPayWay];
            }
           
            [userStatusInfo.realm commitWriteTransaction];
            block(obj);
        }else {
            block(nil);
        }
        
    }];
}


@end
